package kuaishou

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"sort"
	"strings"
)

// CalcSign 计算参数签名
func CalcSign(params map[string]interface{}, appSecret string) string {
	// 1. 过滤掉空 key 或 nil/空字符串的 value
	filtered := make(map[string]string)
	for k, v := range params {
		if strings.TrimSpace(k) == "" || v == nil {
			continue
		}
		strVal := strings.TrimSpace(toString(v))
		if strVal != "" {
			filtered[k] = strVal
		}
	}

	// 2. 按 key 排序
	keys := make([]string, 0, len(filtered))
	for k := range filtered {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	// 3. 拼接成 key=value&key2=value2...
	var sb strings.Builder
	for i, k := range keys {
		if i > 0 {
			sb.WriteString("&")
		}
		sb.WriteString(k + "=" + filtered[k])
	}

	// 4. 加上 appSecret
	signStr := sb.String() + appSecret

	// 5. MD5 签名
	h := md5.New()
	h.Write([]byte(signStr))
	return hex.EncodeToString(h.Sum(nil))
}

// toString 安全转 string（防止接口中 float/int/bool 类型等）
func toString(val interface{}) string {
	switch v := val.(type) {
	case string:
		return v
	case []byte:
		return string(v)
	default:
		return strings.TrimSpace(strings.Trim(strings.ReplaceAll(strings.TrimSpace(fmt.Sprintf("%v", v)), "\n", ""), "\""))
	}
}
